package com.kylin.core.user.event.listener;

import com.kylin.core.user.event.repository.UserDataHandler;
import com.kylin.core.user.query.handler.UserInfoTranslator;
import com.kylin.dal.entity.user.UserWechatEntry;
import com.kylin.domain.user.command.CreateWechatUserCommand;
import com.kylin.domain.user.command.FindUserByOpenIdCommand;
import com.kylin.domain.user.command.UpdateUserPhoneCommand;
import com.kylin.domain.user.command.UpdateWechatUserCommand;
import com.kylin.domain.user.vo.WechatUserInfoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.axonframework.commandhandling.CommandHandler;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author Damon S.
 * @version v1.0.1
 * @date 2020年11月24日 22:00
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class UserCommandHandler {

    private final UserDataHandler userDataHandler;
    private final UserInfoTranslator translator;

    @CommandHandler
    public WechatUserInfoVO handle(CreateWechatUserCommand command) {
        UserWechatEntry entry = userDataHandler.findUserByOpenId(
                FindUserByOpenIdCommand.builder()
                        .openId(command.getOpenId())
                        .build()
        );
        if (Objects.isNull(entry)) {
            entry = userDataHandler.createNew(command);
        }
        return translator.toWechatUserInfoVO(entry);
    }

    @CommandHandler
    public Integer handle(UpdateWechatUserCommand command) {
        return userDataHandler.updateUserInfo(command);
    }

    @CommandHandler
    public Integer handle(UpdateUserPhoneCommand command) {
        return userDataHandler.updateUserPhone(command);
    }
}
